import React from "react";
//import { useSelector } from "react-redux";
import { Link,useParams } from 'react-router-dom';
import PostAuthor from '../../components/PostAuthor'
import TimeAgo from '../../components/TimeAgo'
//import { selectPostById } from "./postsSlice";
import { useGetPostQuery } from "../api/apiSlice";
import Spinner from "../../components/Spinner";
import ReactionButtons from '../../components/ReactionButtons'

// const SinglePostPage = () => {
//     const { postId } = useParams();

//     // const post = useSelector((state) =>
//     //     state.posts.find((post) => post.id === postId)
//     // );

//     const post = useSelector((state) => selectPostById(state, postId));


//     if (!post) {
//         return (
//         <section>
//             <h2>页面未找到！</h2>
//         </section>
//         );
//     }

//     return (
//         <section>
//         <article className="post">
//             <h2>{post.title}</h2>
//             <p className="post-content">{post.content}</p>
//             <Link to={`/editPost/${post.id}`} className="button">
//                 Edit Post
//             </Link>
//             <div>
//                 <PostAuthor userId={post.user} timestamp={post.date}/>
//             </div>
//             <TimeAgo />
//         </article>
//         </section>
//     );
// };

const SinglePostPage = () => {
    const { postId } = useParams();
    // const post = useSelector((state) => selectPostById(state, postId));
    const { data: post, isFetching, isSuccess } = useGetPostQuery(postId);



    // if (!post) {
    //     return (
    //     <section>
    //         <h2>页面未找到！</h2>
    //     </section>
    //     );
    // }

    let content;
    if (isFetching) {
        content = <Spinner text="Loading..." />;
    } else if (isSuccess) {
        content = (
            <article className="post">
                <h2>{post.title}</h2>
                <div>
                <PostAuthor userId={post.user} />
                <TimeAgo timestamp={post.date} />
                </div>
                <p className="post-content">{post.content}</p>
                <ReactionButtons post={post} />
                <Link to={`/editPost/${post.id}`} className="button">
                Edit Post
                </Link>
            </article>
        );
    }

    return <section>{content}</section>;
};

export default SinglePostPage;